from django import  forms
from . import models,tools,const
from django.db.models import Count,Max,Min,Avg,F,Q
import json
import django_redis



class RegisterForm(forms.Form):
    phone=forms.CharField(min_length=11,max_length=15)
    email=forms.EmailField(max_length=30,min_length=6)
    password = forms.CharField(min_length=6, max_length=15)
    cpassword = forms.CharField(min_length=6, max_length=15)


    def clean_username(self):
        email=self.data.get("email")
        if models.User.objects.filter(email=email):
            self.add_error("email","email已经存在")
        return email

    def clean_phone(self):
        phone=self.data.get("phone")
        if models.User.objects.filter(phone=phone):
            self.add_error("phone","phone已经存在")
        return phone

    def clean(self):
        password = self.cleaned_data.get("password")
        cpassword = self.cleaned_data.get("cpassword")
        if password and password == cpassword:
            password = tools.md5(password)
            self.cleaned_data["password"] = password
            self.cleaned_data.pop("cpassword")
        else:
            self.add_error("password", "两次输入的密码不一致")

        return self.cleaned_data

class RegisterForm2(forms.ModelForm):
    class Meta:
        model = models.User#对应的model
        fields = '__all__'


class LoginForm(forms.Form):
    username = forms.CharField(min_length=6,max_length=30)
    password = forms.CharField(min_length=6,max_length=30)


    def clean(self):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")
        user = models.User.objects.filter(Q(email=username) | Q(phone=username)).first()
        if not user:
            self.add_error("user", "用户不存在")
            return
        md5_password = tools.md5(password)
        if md5_password != user.password:
            self.add_error("password", "密码不正确")
            return
        self.user = user
        return self.cleaned_data

class PayForm(forms.Form):
    token = forms.CharField(min_length=32,max_length=32)
    money = forms.IntegerField()

    def clean(self):
        token = self.cleaned_data.get("token")
        r = django_redis.get_redis_connection()
        user = r.get(const.login_key_prefix+token)
        if not user:
            self.add_error("token","用户未登录")
            return
        user_dict = json.loads(user)
        self.user_dict = user_dict

        money = self.cleaned_data.get("money")
        user_obj = models.User.objects.get(id=user_dict.get("user_id"))
        if user_obj.money < money:
            self.add_error("money","余额不足")
            return
        self.user_obj=user_obj
        return self.cleaned_data



